#include "Thread.h"
#include "CurrentThread.h"

#include <assert.h>
#include <memory>
#include <semaphore.h>

std::atomic<int32_t> Thread::numCreated_;

Thread::Thread(ThreadFunc func, const std::string &name)
    :started_(false),
    joined_(false),
    pthreadId_(0),
    tid_(0),
    func_(std::move(func)),
    name_(name)
{
    setDefaultName();
}

Thread::~Thread()
{
    if(started_ && !joined_)
    {
        thread_->detach(); 
    }
}

void Thread::start()
{
    assert(!started_);
    started_ = true;
    sem_t sem;
    sem_init(&sem,false,0);
    thread_ = std::shared_ptr<std::thread>(new std::thread([&]{
        // 获取线程的tid
        tid_ = CurrentThread::tid();
        sem_post(&sem);
        func_();
    }));

    sem_wait(&sem);
}

void Thread::join()
{
    assert(started_);
    joined_ = true;
    thread_->join();
}

void Thread::setDefaultName()
{
    int num = ++numCreated_;
    if(name_.empty())
    {
        char buf[32];
        snprintf(buf,sizeof buf,"Thread%d",num);
        name_ = buf;
    }
}
